'use strict';

async function inputWords(input, words) {
  await this.delay(100)
  input.dispatchEvent(new Event('focus', {bubbles: true}))
  input.value = ''
  input.dispatchEvent(new Event('input', {bubbles: true}))
  console.log(`清空输入框`)
  input.dispatchEvent(new Event('change', { bubbles: true }));
  await this.delay(100)
  var promiseArray = [];
  for (let index = 0; index < words.length; index++) {
    const word = words[index];
    promiseArray.push(word)
  }

  await promiseArray.reduce((prevPromise, curValue) => {
    return prevPromise.then(() => {
      input.value = input.value + curValue
      input.dispatchEvent(new Event('input', {bubbles: true}))
      console.log(`已经键入 => ${curValue}`)
      input.dispatchEvent(new Event('change', { bubbles: true }));
      return this.delay(100)
    })
  }, Promise.resolve())

  input.dispatchEvent(new Event('blur', {bubbles: true}))
}

function isVisible(dom) {
  return dom.getBoundingClientRect().width > 0 && dom.getBoundingClientRect().height > 0;
}

function querySelector(selectorName) {
  var doms = document.querySelectorAll(selectorName)

  for (let index = 0; index < doms.length; index++) {
    const element = doms[index];
    if(isVisible(element)) {
      return element
    }
  }
  return null
}

// 根据站点做不同的处理
var __RUN_SCRIPT = async function() {
  if(this.storageKey == 'carType') {
    try {
      var input = querySelector(this.selectorName)
      if(!input) return
      
      input.parentElement.parentElement.parentElement.querySelector('button').click()
      
      await this.delay(1200)
      
      var input2 = querySelector('.invoice-project__drawer.t-drawer--open form input')
      input2.value = this.targetValue || ''
      input2.dispatchEvent(new Event('input', { bubbles: true }));
      input2.dispatchEvent(new Event('change', { bubbles: true }));
      input2.dispatchEvent(new Event('blur', { bubbles: true }));
      
      await this.delay(10)
      
      var buttons = document.querySelectorAll('.invoice-project__drawer.t-drawer--open form button')
      buttons[1].click()
      
      await this.delay(1500)
  
      var okButton = document.querySelectorAll('.invoice-project__drawer.t-drawer--open .button-text.primary-button__text')[0]
      okButton.click()
    } catch (error) {
      var mask = querySelector('.invoice-project__drawer.t-drawer--open .t-drawer__mask')
      if(mask) mask.click()
    }
  }

  if(this.storageKey == 'carPrice' || this.storageKey === 'buyAddress') {
    var input = querySelector(this.selectorName)
    if(!input) return
    var value = this.targetValue || ''
    await inputWords.call(this, input, value)
  }
  
  if(this.storageKey == 'saleType') {
    var blueInvoice = document.querySelector('div.blue-invoice')
    var checkboxList = document.querySelectorAll('div.blue-invoice label.t-checkbox')
    if(blueInvoice && blueInvoice.style.display == 'none') {
      checkboxList = document.querySelectorAll('div.invoice-parvalue label.t-checkbox')
    }

    var checkbox1 = checkboxList[1]
    if(this.targetValue === 'PERSONAL') {
      // 选中是否自然人
      if(!checkbox1.classList.contains('t-is-checked')) {
        checkbox1.click()
        await this.delay(1000)
        var button = querySelector('.stopPrompDialog button.t-button')
        if(button) {
          button.click()
          await this.delay(150)
        }
      }
      // 填写身份证信息
      await this.delay(150)
      var saleIDCard = this.getSelectorByStorageKey("saleIDCard")
      var saleCode = this.getSelectorByStorageKey("saleCode")
      await this.setDomValue(saleIDCard.selectorName, saleCode.targetValue, true)
    } else {
      // 去掉选中
      if(checkbox1.classList.contains('t-is-checked')) {
        checkbox1.click()
        await this.delay(1000)
        var button = querySelector('.stopPrompDialog button.t-button')
        if(button) {
          button.click()
          await this.delay(150)
        }
      }
      // 填写企业自然人纳税人识别号
      await this.delay(150)
      var saleCode = this.getSelectorByStorageKey("saleCode")
      await this.setDomValue(saleCode.selectorName, saleCode.targetValue, true)
    }
  }
  if(this.storageKey == 'buyType') {

    var blueInvoice = document.querySelector('div.blue-invoice')
    var checkboxList = document.querySelectorAll('div.blue-invoice label.t-checkbox')
    if(blueInvoice && blueInvoice.style.display == 'none') {
      checkboxList = document.querySelectorAll('div.invoice-parvalue label.t-checkbox')
    }

    var checkbox0 = checkboxList[0]
    if(this.targetValue === 'PERSONAL') {
      // 选中是否自然人
      if(!checkbox0.classList.contains('t-is-checked')) {
        checkbox0.click()
        await this.delay(1000)
        var button = querySelector('.stopPrompDialog button.t-button')
        if(button) {
          button.click()
          await this.delay(150)
        }
      }
      // 填写身份证信息
      await this.delay(150)
      var buyCode = this.getSelectorByStorageKey("buyCode")
      var buyIDCard = this.getSelectorByStorageKey("buyIDCard")
      await this.setDomValue(buyIDCard.selectorName, buyCode.targetValue, true)
    } else {
      // 去掉选中
      if(checkbox0.classList.contains('t-is-checked')) {
        checkbox0.click()
        await this.delay(1000)
        var button = querySelector('.stopPrompDialog button.t-button')
        if(button) {
          button.click()
          await this.delay(150)
        }
      }
      // 填写企业自然人纳税人识别号
      await this.delay(150)
      var buyCode = this.getSelectorByStorageKey("buyCode")
      await this.setDomValue(buyCode.selectorName, buyCode.targetValue, true)
    }
  }
}
// 执行单个复制程序
window.__RUN_SCRIPT = __RUN_SCRIPT
// 是否中断
window.__RUN_CONTINUE =  async function() {
  return new Promise((resolve, reject) => {
    // 这里获取listenStatus中保存的值，如果是未开票状态，则提示先点击打印交易票之后，再来开票。
    $dataCopyStorage.get('listenStatus', (value)=> {
      if(value != 'YES') {
        alert("请先点击“打印交易票”")
      }
      resolve(value === 'YES')
    })
  })
}
